﻿using System;
using System.Collections.Generic;
using ChiakiYu.Core.Domain.Repositories;
using ChiakiYu.Model.Permissions;
using ChiakiYu.Model.Roles;
using ChiakiYu.Model.Users;

namespace ChiakiYu.Service.Authorization
{
    public class AuthorizationService : IAuthorizationService
    {
        private readonly IRepository<Role, int> _roleRepository;
        private readonly IRepository<User, long> _userRepository;
        private readonly IRepository<RolePermission, string> _rolePermissionRepository;
        private readonly IRepository<UserPermission, string> _userPermissionRepository;

        public AuthorizationService(
            IRepository<Role, int> roleRepository,
            IRepository<User, long> userRepository,
            IRepository<RolePermission, string> rolePermissionRepository,
            IRepository<UserPermission, string> userPermissionRepository)
        {
            _roleRepository = roleRepository;
            _userRepository = userRepository;
            _rolePermissionRepository = rolePermissionRepository;
            _userPermissionRepository = userPermissionRepository;
        }

        public IEnumerable<Permission> GetRolePermissions(int roleId)
        {
            //取角色
            var role = _roleRepository.Get(roleId);
            //取角色权限列表        
            var rolePermissions = role.Permissions;
            return rolePermissions;
        }

        public IEnumerable<Permission> GetUserPermissions(long userId)
        {
            //用户权限集合
            var userPermissions = new List<Permission>();
            //取用户
            var user = _userRepository.Get(userId);
            //取用户所属角色的所有权限
            foreach (var item in user.Roles)
            {
                //取角色权限
                var rolePermissions = item.Permissions;
                //插入用户权限
                userPermissions.AddRange(rolePermissions);
            }
            return userPermissions;
        }


        public bool DeleteRolePermissions(int roleId)
        {
            try
            {
                _rolePermissionRepository.Delete(n => n.RoleId == roleId);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool DeleteUserPermissions(long userId)
        {
            try
            {
                _userPermissionRepository.Delete(n => n.UserId == userId);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}